import { useState, useEffect } from 'react';
import { cn } from '@/lib/utils';
import { HolidayStorage, formatDateForHoliday } from '@/lib/utils';

interface CalendarProps {
  isOpen: boolean;
  onClose: () => void;
}

interface Holiday {
  date: string;
  name: string;
  isCustom: boolean;
}

// 获取指定月份的天数
const getDaysInMonth = (year: number, month: number): Date[] => {
  const days = [];
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  
  // 添加月初前的空白日期
  const firstDayOfWeek = firstDay.getDay() || 7; // 将周日从0改为7
  for (let i = 1; i < firstDayOfWeek; i++) {
    days.push(null);
  }
  
  // 添加当月日期
  for (let i = 1; i <= lastDay.getDate(); i++) {
    days.push(new Date(year, month, i));
  }
  
  return days;
};

export default function Calendar({ isOpen, onClose }: CalendarProps) {
  const [currentDate, setCurrentDate] = useState(new Date());
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);
  const [daysInMonth, setDaysInMonth] = useState<Date[]>([]);
  const [holidays, setHolidays] = useState<Holiday[]>([]);
  const [selectedYear, setSelectedYear] = useState(currentDate.getFullYear());
  const [selectedMonth, setSelectedMonth] = useState(currentDate.getMonth());
  const [showAddHolidayModal, setShowAddHolidayModal] = useState(false);
  const [holidayName, setHolidayName] = useState('');
  
  // 获取年份选择范围（当前年份前后10年）
  const getYearOptions = () => {
    const currentYear = new Date().getFullYear();
    const years = [];
    for (let i = currentYear - 10; i <= currentYear + 10; i++) {
      years.push(i);
    }
    return years;
  };
  
  // 获取月份名称
  const getMonthName = (month: number) => {
    return new Date(0, month).toLocaleDateString('zh-CN', { month: 'long' });
  };
  
  // 当currentDate变化时重新计算月份天数
  useEffect(() => {
    setDaysInMonth(getDaysInMonth(currentDate.getFullYear(), currentDate.getMonth()));
    setSelectedYear(currentDate.getFullYear());
    setSelectedMonth(currentDate.getMonth());
    
    // 默认选中今天
    const today = new Date();
    if (
      today.getFullYear() === currentDate.getFullYear() &&
      today.getMonth() === currentDate.getMonth()
    ) {
      setSelectedDate(today);
    }
  }, [currentDate]);
  
  // 加载节日数据
  useEffect(() => {
    const loadHolidays = () => {
      const storedHolidays = HolidayStorage.get();
      setHolidays(storedHolidays);
    };
    
    loadHolidays();
  }, []);
  
  // 当年份或月份变化时更新日历
  useEffect(() => {
    const newDate = new Date(selectedYear, selectedMonth, 1);
    setCurrentDate(newDate);
    setDaysInMonth(getDaysInMonth(selectedYear, selectedMonth));
  }, [selectedYear, selectedMonth]);
  
  // 切换到上一个月
  const prevMonth = () => {
    setCurrentDate(prev => {
      const newDate = new Date(prev.getFullYear(), prev.getMonth() - 1, 1);
      setSelectedYear(newDate.getFullYear());
      setSelectedMonth(newDate.getMonth());
      return newDate;
    });
  };
  
  // 切换到下一个月
  const nextMonth = () => {
    setCurrentDate(prev => {
      const newDate = new Date(prev.getFullYear(), prev.getMonth() + 1, 1);
      setSelectedYear(newDate.getFullYear());
      setSelectedMonth(newDate.getMonth());
      return newDate;
    });
  };
  
  // 选择日期
  const handleDateSelect = (date: Date) => {
    setSelectedDate(date);
    
    // 检查是否是自定义节日，如是则填充名称
    const dateStr = formatDateForHoliday(date);
    const customHoliday = holidays.find(h => h.date === dateStr && h.isCustom);
    if (customHoliday) {
      setHolidayName(customHoliday.name);
    } else {
      setHolidayName('');
    }
  };
  
  // 检查是否是今天
  const isToday = (date: Date): boolean => {
    const today = new Date();
    return (
      date.getDate() === today.getDate() &&
      date.getMonth() === today.getMonth() &&
      date.getFullYear() === today.getFullYear()
    );
  };
  
  // 检查是否是选中日期
  const isSelected = (date: Date): boolean => {
    return selectedDate && 
      date.getDate() === selectedDate.getDate() &&
      date.getMonth() === selectedDate.getMonth() &&
      date.getFullYear() === selectedDate.getFullYear();
  };
  
  // 检查日期是否是节日
  const getHolidayForDate = (date: Date): Holiday | null => {
    const dateStr = formatDateForHoliday(date);
    return holidays.find(h => h.date === dateStr) || null;
  };
  
  // 添加或更新自定义节日
  const handleAddHoliday = () => {
    if (!selectedDate || !holidayName.trim()) return;
    
    const dateStr = formatDateForHoliday(selectedDate);
    HolidayStorage.add({ date: dateStr, name: holidayName.trim() });
    
    // 更新本地状态
    setHolidays(HolidayStorage.get());
    setShowAddHolidayModal(false);
    setHolidayName('');
  };
  
  // 删除自定义节日
  const handleDeleteHoliday = (date: Date) => {
    const dateStr = formatDateForHoliday(date);
    HolidayStorage.remove(dateStr);
    setHolidays(HolidayStorage.get());
    setHolidayName('');
  };
  
  // 打开添加节日模态框
  const openAddHolidayModal = (date: Date) => {
    setSelectedDate(date);
    const dateStr = formatDateForHoliday(date);
    const customHoliday = holidays.find(h => h.date === dateStr && h.isCustom);
    
    if (customHoliday) {
      setHolidayName(customHoliday.name);
    } else {
      setHolidayName('');
    }
    
    setShowAddHolidayModal(true);
  };
  
   if (!isOpen) return null;
   
   return (
     <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4" onClick={onClose}>
       <div 
         className="bg-white dark:bg-gray-800 rounded-xl shadow-lg w-full max-w-md"
         onClick={(e) => e.stopPropagation()}
       >
         {/* 日历头部 */}
         <div className="p-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
           <h3 className="text-lg font-semibold text-gray-900 dark:text-white">日历</h3>
           <button 
             onClick={onClose}
             className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
           >
             <i className="fa-solid fa-times"></i>
           </button>
         </div>
         
         {/* 年份月份导航 */}
         <div className="p-4 flex justify-between items-center">
           <button 
             onClick={prevMonth}
             className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
             aria-label="上一个月"
           >
             <i className="fa-solid fa-chevron-left"></i>
           </button>
           
           <div className="flex items-center space-x-3">
             {/* 年份选择 */}
             <select
               value={selectedYear}
               onChange={(e) => setSelectedYear(Number(e.target.value))}
               className="bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
             >
               {getYearOptions().map(year => (
                 <option key={year} value={year}>{year}</option>
               ))}
             </select>
             
             {/* 月份选择 */}
             <select
               value={selectedMonth}
               onChange={(e) => setSelectedMonth(Number(e.target.value))}
               className="bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
             >
               {Array.from({ length: 12 }, (_, i) => i).map(month => (
                 <option key={month} value={month}>{getMonthName(month)}</option>
               ))}
             </select>
           </div>
           
           <button 
             onClick={nextMonth}
             className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
             aria-label="下一个月"
           >
             <i className="fa-solid fa-chevron-right"></i>
           </button>
         </div>
         
         {/* 星期标题 */}
         <div className="grid grid-cols-7 px-4 mb-2">
           {['日', '一', '二', '三', '四', '五', '六'].map((day, index) => (
             <div key={index} className="text-center text-sm font-medium py-2">
               <span className={index === 0 || index === 6 ? "text-red-500 dark:text-red-400" : "text-gray-500 dark:text-gray-400"}>
                 {day}
               </span>
             </div>
           ))}
         </div>
         
         {/* 日历网格 */}
         <div className="grid grid-cols-7 px-4 pb-4">
           {daysInMonth.map((date, index) => {
             if (!date) {
               // 空白单元格（月初前或月末后的日期）
               return <div key={index} className="h-16"></div>;
             }
             
             const holiday = getHolidayForDate(date);
             const isWeekend = date.getDay() === 0 || date.getDay() === 6;
             
             return (
               <div key={index} className="h-16 flex flex-col items-center justify-start py-1 relative group">
                 <button
                   onClick={() => handleDateSelect(date)}
                   className={cn(
                     "flex items-center justify-center rounded-full w-10 h-10 transition-colors",
                     isToday(date) 
                       ? "bg-blue-500 text-white font-medium" 
                       : isSelected(date)
                         ? "bg-blue-100 dark:bg-blue-900 text-blue-600 dark:text-blue-400 font-medium"
                         : isWeekend
                           ? "text-red-500 dark:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700"
                           : "hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-900 dark:text-gray-100"
                   )}
                 >
                   {date.getDate()}
                 </button>
                 
                 {/* 节日标签 */}
                 {holiday && (
                   <div className={`text-[10px] mt-1 px-1 rounded ${
                     holiday.isCustom 
                       ? 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300' 
                       : 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300'
                   }`}>
                     {holiday.name}
                   </div>
                 )}
                 
                 {/* 添加节日按钮 */}
                 {isSelected(date) && (
                   <button
                     onClick={() => openAddHolidayModal(date)}
                     className="absolute bottom-0 text-blue-500 dark:text-blue-400 text-xs"
                   >
                     <i className="fa-solid fa-plus-circle"></i>
                   </button>
                 )}
               </div>
             );
           })}
         </div>
       </div>
       
       {/* 添加/编辑节日模态框 */}
       {showAddHolidayModal && selectedDate && (
         <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4" onClick={() => setShowAddHolidayModal(false)}>
           <div 
             className="bg-white dark:bg-gray-800 rounded-xl shadow-lg w-full max-w-md p-5"
             onClick={(e) => e.stopPropagation()}
           >
             <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
               {holidayName ? '编辑节日' : '添加节日'}
             </h3>
             
             <div className="mb-4">
               <p className="text-sm text-gray-500 dark:text-gray-400 mb-2">
                 日期: {selectedDate.getFullYear()}年{selectedDate.getMonth() + 1}月{selectedDate.getDate()}日
               </p>
               <input
                 type="text"
                 value={holidayName}
                 onChange={(e) => setHolidayName(e.target.value)}
                 placeholder="输入节日名称"
                 className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100"
               />
             </div>
             
             <div className="flex justify-end space-x-3">
               {holidayName && (
                 <button
                   onClick={() => handleDeleteHoliday(selectedDate)}
                   className="px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
                 >
                   删除
                 </button>
               )}
               
               <button
                 onClick={() => setShowAddHolidayModal(false)}
                 className="px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
               >
                 取消
               </button>
               
               <button
                 onClick={handleAddHoliday}
                 className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                 disabled={!holidayName.trim()}
               >
                 保存
               </button>
             </div>
           </div>
         </div>
       )}
     </div>
   );
 }